import { 
  Controller, 
  Get, 
  Post, 
  Delete,
  Body, 
  Query, 
  Param, 
  UseGuards, 
  Request, 
  HttpException, 
  HttpStatus,
  UseInterceptors,
  UploadedFile,
  BadRequestException
} from '@nestjs/common';
import { CreateActivityDto } from './dto/create-activity.dto';
import { Activity } from './entities/activity.entity';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { ActivityService, ActivityStatus } from './activity.service';
import { Activity } from './entities/activity.entity';
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
import { MoreThan, LessThanOrEqual, LessThan, MoreThanOrEqual } from 'typeorm';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { v4 as uuidv4 } from 'uuid';

@ApiTags('活动')
@Controller('activity')
export class ActivityController {
  constructor(private readonly activityService: ActivityService) {}

  @Get(':id/join/check')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '检查活动报名状态' })
  async checkJoinStatus(
    @Param('id') id: number,
    @Request() req,
  ) {
    try {
      const isJoined = await this.activityService.checkJoinStatus(id, req.user.id);
      return {
        code: 200,
        data: { isJoined },
        message: 'success'
      };
    } catch (error) {
      console.error('检查报名状态失败:', error);
      throw error;
    }
  }

  @Get(':id/favorite/check')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '检查活动收藏状态' })
  async checkFavoriteStatus(
    @Param('id') id: number,
    @Request() req,
  ) {
    const isFavorite = await this.activityService.checkFavoriteStatus(id, req.user.id);
    return {
      code: 200,
      data: { isFavorite },
      message: 'success'
    };
  }

  @Get('list')
  @ApiOperation({ summary: '获取活动列表' })
  @ApiQuery({ name: 'type', enum: ['upcoming', 'ongoing', 'finished'], required: false })
  async findAll(
    @Query('page') page: number = 1,
    @Query('pageSize') pageSize: number = 10,
    @Query('type') type?: ActivityStatus
  ) {
    try {
      const result = await this.activityService.findAll(page, pageSize, type)
      return {
        code: 200,
        data: result,
        message: 'success'
      }
    } catch (error) {
      throw new HttpException({
        code: 500,
        message: error.message || '获取活动列表失败',
        data: null
      }, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }

  @Get('detail/:id')
  @ApiOperation({ summary: '获取活动详情' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: Activity
  })
  @ApiResponse({
    status: 404,
    description: '活动不存在'
  })
  async findOne(@Param('id') id: number) {
    return this.activityService.findOne(id);
  }

  @Get('user/created')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth('JWT-auth')
  @ApiOperation({ summary: '获取用户创建的活动' })
  @ApiQuery({ name: 'page', required: false, type: Number, description: '页码' })
  @ApiQuery({ name: 'pageSize', required: false, type: Number, description: '每页数量' })
  @ApiResponse({
    status: 200,
    description: '获取成功',
    type: [Activity]
  })
  async getUserCreated(
    @Request() req,
    @Query('page') page: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    try {
      const result = await this.activityService.findByCreator(req.user.id, page, pageSize);
      return {
        code: 200,
        data: result,
        message: 'success'
      };
    } catch (error) {
      throw new HttpException({
        code: 500,
        message: error.message || '获取创建的活动列表失败',
        data: null
      }, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }


  @Get('debug/status')
  @ApiOperation({ summary: '调试用-获取活动状态统计' })
  async getActivityStatusStats() {
    return this.activityService.getActivityStatusStats();
  }

  @Post(':id/favorite')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '收藏活动' })
  async favoriteActivity(
    @Param('id') id: number,
    @Request() req,
  ) {
    await this.activityService.favoriteActivity(id, req.user.id);
    return {
      code: 200,
      message: 'success'
    };
  }

  @Delete(':id/favorite')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '取消收藏活动' })
  async unfavoriteActivity(
    @Param('id') id: number,
    @Request() req,
  ) {
    await this.activityService.unfavoriteActivity(id, req.user.id);
    return {
      code: 200,
      message: 'success'
    };
  }

  @Get('user/favorites')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户收藏的活动列表' })
  async getUserFavorites(
    @Request() req,
    @Query('page') page: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    const result = await this.activityService.getUserFavorites(req.user.id, page, pageSize);
    return {
      code: 200,
      data: result,
      message: 'success'
    };
  }

  // 添加图片上传接口
  @Post('upload-image')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '上传活动图片' })
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads/activities',
        filename: (req, file, cb) => {
          // 生成唯一文件名
          const uniqueSuffix = uuidv4();
          const ext = extname(file.originalname);
          cb(null, `${uniqueSuffix}${ext}`);
        },
      }),
      fileFilter: (req, file, cb) => {
        // 只允许上传图片
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
          return cb(new Error('只允许上传图片文件!'), false);
        }
        cb(null, true);
      },
      limits: {
        fileSize: 5 * 1024 * 1024, // 限制文件大小为5MB
      },
    }),
  )
  async uploadActivityImage(
    @UploadedFile() file,
    @Request() req,
  ) {
    try {
      if (!file) {
        throw new HttpException('请上传文件', HttpStatus.BAD_REQUEST);
      }

      // 构建文件URL
      const baseUrl = process.env.NODE_ENV === 'production' ? 'https://hdq-activity.hduhelp.com' : 'http://localhost:3000';
      const fileUrl = `/uploads/activities/${file.filename}`;

      return {
        code: 200,
        data: { url: fileUrl },
        message: '上传成功'
      };
    } catch (error) {
      throw new HttpException({
        code: 500,
        message: error.message || '上传失败',
        data: null
      }, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @Post('create')
  @UseGuards(JwtAuthGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: '创建活动' })
  @ApiResponse({
    status: 200,
    description: '创建成功',
    schema: {
      properties: {
        code: { type: 'number', example: 200 },
        data: { type: 'object', ref: Activity },
        message: { type: 'string', example: '创建成功' }
      }
    }
  })
  @ApiResponse({
    status: 400,
    description: '请求参数错误',
    schema: {
      properties: {
        code: { type: 'number', example: 400 },
        message: { type: 'string', example: '参数验证失败' },
        data: { type: 'null', example: null }
      }
    }
  })
  async create(@Body() createActivityDto: CreateActivityDto, @Request() req) {
    try {
      const activity = await this.activityService.create(req.user.id, createActivityDto);
      return {
        code: 200,
        data: activity,
        message: '创建成功'
      };
    } catch (error) {
      if (error instanceof BadRequestException) {
        throw new HttpException({
          code: 400,
          message: error.message,
          data: null
        }, HttpStatus.BAD_REQUEST);
      }
      throw new HttpException({
        code: 500,
        message: error.message || '创建活动失败',
        data: null
      }, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
























